<template>
	<div class="new-page" :style="`min-height: ${pageMinHeight}px`">
		<a-card style="margin-top: 24px">
			<div slot="title" class="listTitle">
				<span>文章列表</span>
				<a-button @click="showModal(1, null)" type="primary">添加文章</a-button>
			</div>
			<a-list item-layout="vertical" size="large" :pagination="{ pageSize: 10 }" :data-source="articleList">
				<template #renderItem="item">
					<a-card hoverable style="width: 360px">
						<template #cover>
							<div class="img">
								<img alt="example" :src="item.logo" />
							</div>
						</template>
						<template slot="actions" class="ant-card-actions">
							<!-- <a-icon key="setting" type="setting" /> -->
							<a-icon key="edit" type="edit" @click="showModal(2, item)" />
							<a-popconfirm title="确认删除该文章吗?" ok-text="确认" cancel-text="取消" @confirm="handleDel(item.id)">
								<a-icon key="delete" type="delete" />
							</a-popconfirm>
						</template>
						<a-card-meta :title="item.title" :description="item.describe">
							<!-- <template #avatar>
								<a-avatar src="https://joeschmoe.io/api/v1/random" />
							</template> -->
						</a-card-meta>
					</a-card>
				</template>
			</a-list>

			<!-- 修改弹出 -->
			<!-- wrap-class-name="full-modal" 全屏 -->
			<a-modal v-model:visible="visible" width="50%" :maskClosable='false' :closable='false'
				:title="modalTitle == 1 ? '修改文章' : '新增文章'">
				<div>
					<a-form>
						<a-form-item label="文章封面" :labelCol="{ span: 3 }" :wrapperCol="{ span: 20 }">
							<div class="clearfix coverImgBox">
								<a-upload class="upload" :customRequest="customRequest" list-type="picture-card"
									:show-upload-list="false">
									<img class="logo" v-if="logo" :src="logo" alt="avatar" />
									<div v-else>
										<a-icon type="plus" />
										<div class="ant-upload-text">
											上传封面图
										</div>
									</div>
								</a-upload>
								<a-icon class="delete" key="close" type="close" v-if="logo" @click.stop="coverImgDel" />
							</div>
						</a-form-item>
						<a-form-item label="文章标题" :labelCol="{ span: 3 }" :wrapperCol="{ span: 20 }">
							<a-input v-model="title" placeholder="请输入文章标题" />
						</a-form-item>
						<a-form-item label="推荐首页" :labelCol="{ span: 3 }" :wrapperCol="{ span: 20 }">
							<a-radio-group v-model="isTop" name="radioGroup">
								<a-radio value="1">是</a-radio>
								<a-radio value="0">否</a-radio>
							</a-radio-group>
						</a-form-item>
						<a-form-item label="文章简介" :labelCol="{ span: 3 }" :wrapperCol="{ span: 20 }">
							<a-input v-model="describe" placeholder="请输入文章简介" />
						</a-form-item>
						<a-form-item label="文章内容" :labelCol="{ span: 3 }" :wrapperCol="{ span: 20 }">
							<!-- <a-textarea v-model="info" rows="4" placeholder="请输入文章内容" /> -->
							<div style="border: 1px solid #ccc;">
								<Toolbar style="border-bottom: 1px solid #ccc" :editor="editor"
									:defaultConfig="toolbarConfig" :mode="mode" />
								<Editor style="height: 500px; overflow-y: hidden;" v-model="info"
									:defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated" />
							</div>
						</a-form-item>
					</a-form>
				</div>
				<template #footer>
					<a-button key="back" @click="handleCancel">取消</a-button>
					<a-button key="submit" type="primary" @click="setData">确认</a-button>
				</template>

			</a-modal>
		</a-card>
	</div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { dataSource as ds } from '@/services'
import { mapState } from 'vuex'
export default {
	name: 'Article',
	components: {
		Editor,
		Toolbar
	},
	data() {
		return {
			page: 1,
			conditions: {},
			articleList: [],
			modalTitle: '新增/修改',
			visible: false,
			logo: "",
			title: "",
			describe: "",
			isTop: "",
			coverShow: false,
			projectName: '',
			projectType: undefined,
			details: '',
			itemId: '', //修改时的id
			editor: null,
			info: '<p></p>',
			toolbarConfig: {},
			editorConfig: {
				placeholder: '请输入内容...',
				MENU_CONF: {
					fileName: "file",
					uploadImage: {
						customUpload: async (file, insertFn) => {
							let resultUrl = await this.upload(file);
							insertFn(resultUrl);
						}
					},
					uploadVideo: {
						customUpload: async (file, insertFn) => {
							let resultUrl = await this.upload(file);
							insertFn(resultUrl);
						},
					},
				}
			},
			mode: 'default', // or 'simple'
		}
	},
	computed: {
		...mapState('setting', ['pageMinHeight']),
		desc() {
			return this.$t('description')
		}
	},
	mounted() {
		this.getList();
	},
	beforeDestroy() {
		const editor = this.editor
		if (editor == null) return
		editor.destroy() // 组件销毁时，及时销毁编辑器
	},
	methods: {
		onCreated(editor) {
			this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
		},
		// 上传图片、视频
		upload(file) {
			return new Promise((resolve) => {
				let fd = new FormData()
				fd.append('file', file)
				ds.baseUpload(fd).then(res => {
					resolve(res?.data?.url)
				})
			})

		},
		coverImgDel() {
			this.logo = ""
		},
		// 封面图上传
		customRequest(e) {
			let that = this;
			let fd = new FormData()
			fd.append('file', e.file)
			ds.baseUpload(fd).then(res => {
				const data = res?.data
				that.logo = data?.url
			})
		},
		getList() {
			const that = this
			that.loading = true
			const { page, pageSize, conditions } = that
			ds.getArticleList({ page, pageSize, ...conditions }).then(res => {
				const data = res?.data?.data
				that.articleList = data[0]
				that.total = data[1].total
				that.loading = false
			})
		},
		// 删除列表
		handleDel(id) {
			let that = this
			ds.delArticle({ id: id }).then(res => {
				if (res?.data?.success) {
					that.$message.success('删除成功')
					that.getList()
				}
			})
		},
		handleCancel() {
			this.$nextTick(() => {
				this.clear()
				this.visible = false;
			})
		},
		clear() {
			this.itemId = ''
			this.logo = ''
			this.title = ''
			this.describe = ''
			this.info = ""
			this.sort = ""
		},
		// 显示弹窗：修改/新增
		showModal(type, item) {
			// 弹窗前,先清除页面原有数据;
			if (item) {
				// 修改
				this.$nextTick(() => {
					this.modalTitle = 1
					this.clear()
					this.itemId = item.id
					this.logo = item.logo
					this.title = item.title
					this.describe = item.describe
					this.info = item.info
					this.sort = item.sort
					setTimeout(() => {
						this.visible = true;
					}, 100)
				})
			} else {
				// 新增
				this.$nextTick(() => {
					this.modalTitle = 2
					this.clear()
					setTimeout(() => {
						this.visible = true;
					}, 100)
				})
			}
		},
		// 新增/修改方法
		setData() {
			var that = this;
			if (this.logo == '') {
				this.$message.error('请上传文章封面');
				return false;
			} else if (this.title == '') {
				this.$message.error('请输入文章标题');
				return false;
			} else if (this.describe == '') {
				this.$message.error('请输入文章简介');
				return false;
			} else if (this.info == '') {
				this.$message.error('请输入文章内容');
				return false;
			} else {
				const params = {
					title: this.title,
					describe: this.describe,
					info: this.info,
					logo: this.logo,
					sort: 1,
					isTop: this.isTop
				}
				if (that.modalTitle == 1) {
					params.id = this.itemId
					ds.updateArticle(params).then(res => {
						if (res?.data?.success) {
							this.$message.success('编辑成功')
							this.visible = false
							this.clear()
							this.getList()
							this.$forceUpdate()
						}
					})
				} else {
					ds.addArticle(params).then(res => {
						if (res?.data?.success) {
							this.$message.success('新增成功')
							this.visible = false
							this.getList()
							this.$forceUpdate()
						}
					})
				}
			}
		}
	}
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="less">
.img {
	height: 240px;
	overflow: hidden;

	img {
		width: 100%;
		display: block;
	}
}

.listTitle {
	display: flex;
	justify-content: space-between;
}

.full-modal {
	.ant-modal {
		max-width: 100%;
		top: 0;
		padding-bottom: 0;
		margin: 0;
	}

	.ant-modal-content {
		display: flex;
		flex-direction: column;
		height: calc(100vh);
	}

	.ant-modal-body {
		flex: 1;
	}
}

.ant-list-item-extra {
	display: flex;
	align-items: center;
	justify-content: center;
}

.coverImgBox {
	position: relative;
}

.coverImgBox .delete {
	position: absolute;
	top: 20px;
	right: 20px;
}

.coverImgBox .ant-upload {
	width: 100%;
	height: 400px;
}

.coverImgBox .ant-upload.ant-upload-select-picture-card {
	float: none;
	margin: 0 auto;
}

.coverImgBox .ant-upload-list-picture-card-container {
	float: none;
	margin: 0 auto;
}

.ant-list {
	.ant-spin-container {
		.ant-list-items {
			display: flex;

		}
	}
}
</style>
